import React, {Component} from "react";
import Text from "antd/es/typography/Text";
import {Button, Icon, Input, Modal, Table} from "antd";
import {inject, observer} from "mobx-react";
import TextArea from "antd/es/input/TextArea";


// todo: 绑定有bug
export default @inject('store') @observer
class Seed extends Component {
    seedColumns = [
        {
            title: 'ID',
            dataIndex: 'ID',
            key: 'ID',
        },
        {
            title: '创建时间',
            dataIndex: 'CreatedAt',
            key: 'CreatedAt',
        },
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: 'Url',
            dataIndex: 'url',
            key: 'url',
        },
        {
            title: '解析方法名',
            dataIndex: 'function_name',
            key: 'function_name',
        },
        {
            title: '操作',
            render: (item) => (
                <div>
                    <Button type={"danger"} size={"small"} onClick={() => this.deleteSeed(item)}
                            style={{marginRight: 5}}>删除</Button>
                    <Button size={"small"} onClick={() => this.output(item)}
                            style={{marginRight: 5}}>导出</Button>
                    <Button type={"primary"} size={"small"}
                            onClick={() => this.seedManage(item)}
                    >管理</Button>
                </div>)
        },
    ];

    settingColumns = [
        {
            title: 'ID',
            dataIndex: 'ID',
            key: 'ID',
        },
        {
            title: 'Host',
            dataIndex: 'host',
            key: 'host',
        },
        {
            title: '程序ID',
            dataIndex: 'worker_id',
            key: 'worker_id',
        },
        {
            title: '程序状态',
            dataIndex: 'status',
            key: 'status',
            render: (text) => {
                switch (text) {
                    case 0:
                        return <Text>运行中</Text>;
                    case 1:
                        return <Text type={"warning"}>已暂停</Text>;
                    default:
                }
            }
        },
        {
            title: '操作',
            render: (item) => {
                switch (item.status) {
                    case 0:
                        return <div>
                            <Button type={"danger"} size={"small"} style={{marginRight: 5}}
                                    onClick={() => this._pause(item)}>暂停</Button>
                            <Button type={"danger"} size={"small"}
                                    onClick={() => this._bindSeedCancel(item)}>解绑</Button>
                        </div>;
                    case 1:
                        return <div>
                            <Button type={"primary"} size={"small"} style={{marginRight: 5}}
                                    onClick={() => this._begin(item)}>开始</Button>
                            <Button type={"danger"} size={"small"}
                                    onClick={() => this._bindSeedCancel(item)}>解绑</Button>
                        </div>;
                    default:
                }
            }


        },
    ];

    workerColumns = [
        {
            title: 'ID',
            dataIndex: 'ID',
            key: 'ID',
        },
        {
            title: '创建时间',
            dataIndex: 'CreatedAt',
            key: 'CreatedAt',
        },
        {
            title: '更新时间',
            dataIndex: 'UpdatedAt',
            key: 'UpdatedAt',
        },
        {
            title: '机器ID',
            dataIndex: 'machine_id',
            key: 'machine_id',
        },
        {
            title: '机器IP',
            dataIndex: 'machine.ip',
            key: 'machine_ip',
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (text) => {
                switch (text) {
                    case 0:
                        return <Text>运行中</Text>;
                    case 1:
                        return <Text type={"warning"}>已暂停</Text>;
                    default:
                }
            }
        },
    ];

    limit = 5;

    constructor(props) {
        super(props);

        this.state = {
            seeds: [],
            selectedSeed: null,
            seedsCurrent: 0,
            seedsCount: 0,

            outputSelectedSeed: null,
            outputVisible: false,

            addSeedVisible: false,
            addSeedName: '',
            addSeedUrl: '',
            addSeedParams: '',
            addSeedFunctionName: '',

            deleteSeedVisible: false,
            deleteSeed: null,

            settingsVisible: false,
            settings: [],
            settingCurrent: 0,
            settingCount: 0,

            bindSeedVisible: false,
            workers: [],
            workersCount: 0,
            workersCurrent: 0,
            selectedWorker: null,
        }
    }

    componentDidMount() {
        this._getSeeds(0);
    }

    _getWorkers(offset) {
        window.$http.postForm("/worker/gets", {
            offset: offset,
            limit: this.limit,
        }).then(res => {
            if (res.status === 10000) {
                this.setState({workers: res.workers, workersCount: res.count});
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        })
    }

    seedManage(item) {
        this.setState({settingsVisible: true, selectedSeed: item});
        this._getSettings(item, 0);
    }

    _getSettings(item, offset) {
        window.$http.postForm("/nsq/gets/seed", {
            offset: offset,
            limit: this.limit,
            seed_id: item.ID
        }).then(res => {
            if (res.status === 10000) {
                this.setState({settings: res.settings, settingCount: res.count});
                console.log("settings", res.settings);
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        })
    }

    getWorkers() {
        this._getWorkers(0);
        this.setState({bindSeedVisible: true})
    }

    _getSeeds(offset) {
        window.$http.postForm("/seed/gets", {
            offset: offset,
            limit: this.limit,
        }).then(res => {
            if (res.status === 10000) {
                this.setState({seeds: res.seeds, seedsCount: res.count});
                console.log("settings", res.settings);
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        })
    }

    _bindSeed() {
        window.$http.postForm("/worker/bind", {
            worker_id: this.state.selectedWorker.ID,
            seed_id: this.state.selectedSeed.ID,
        }).then(res => {
            if (res.status === 10000) {
                this.setState({bindSeedVisible: false});
                this._getSettings(this.state.selectedSeed, 0);
                // window.$message.success(res);
                // this.setState({seeds: res.seeds, count: res.count});
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        });

    }

    _bindSeedCancel(item) {
        window.$http.postForm("/worker/bindCancel", {
            setting_id: item.ID,
        }).then(res => {
            if (res.status === 10000) {
                window.$message.success("删除成功");
                this._getSettings(this.state.selectedSeed, 0);
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        });

    }

    _addSeed() {
        window.$http.postForm("/seed/add", {
            name: this.state.addSeedName,
            url: this.state.addSeedUrl,
            params: this.state.addSeedParams,
            function_name: this.state.addSeedFunctionName,
        }).then(res => {
            if (res.status === 10000) {
                window.$message.success("添加成功");
                this._getSeeds((this.state.seedsCurrent - 1) * this.limit);
                this.setState({
                    addSeedVisible: false,
                    addSeedName: '', addSeedUrl: '',
                    addSeedParams: '', addSeedFunctionName: ''
                });
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        });
    }

    deleteSeed(item) {
        this.setState({deleteSeed: item, deleteSeedVisible: true})
    }

    _deleteSeed() {
        window.$http.postForm("/seed/del", {
            seed_id: this.state.deleteSeed.ID
        }).then(res => {
            if (res.status === 10000) {
                window.$message.success("删除成功");
                this.setState({deleteSeedVisible: false});
                this._getSeeds((this.state.seedsCurrent - 1) * this.limit);
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        });

    }

    _pause(item) {
        window.$http.postForm("/nsq/pause", {
            nsq_setting_id: item.ID,
        }).then(res => {
            if (res.status === 10000) {
                window.$message.success("暂停成功");
                this._getSettings(this.state.selectedSeed, (this.state.settingCurrent - 1) * this.limit);
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        });

    }

    _begin(item) {
        console.log("item:", item);
        window.$http.postForm("/nsq/begin", {
            nsq_setting_id: item.ID,
        }).then(res => {
            if (res.status === 10000) {
                window.$message.success("启动成功");
                this._getSettings(this.state.selectedSeed, (this.state.settingCurrent - 1) * this.limit);
                return
            }
            window.$message.warn(res.message);
        }).catch(err => {
            window.$message.error(err.message);
        });
    }

    output(item) {
        this.setState({outputSelectedSeed: item, outputVisible: true})
    }

    _output() {
        window.open('/output?seed_id=' + this.state.outputSelectedSeed.ID);
        this.setState({outputSelectedSeed: null, outputVisible: false});
    }

    render() {
        const marginBottom = 10;
        return <>
            <Button type={"primary"} style={{marginLeft: 10, marginBottom: 15}}
                    onClick={() => this.setState({addSeedVisible: true})}><Icon type={'plus'}/>添加任务</Button>
            <Table rowKey={record => record.id}
                   pagination={{
                       total: this.state.seedsCount,
                       current: this.state.seedsCurrent,
                       pageSize: this.limit,
                       onChange: (page) => {
                           this.setState({current: page});
                           this._getSeeds((page - 1) * this.limit);
                       }
                   }}
                   columns={this.seedColumns} dataSource={this.state.seeds}/>

            {
                this.state.outputVisible ?
                    <Modal
                        onOk={() => this._output()}
                        onCancel={() => this.setState({outputVisible: false, outputSelectedSeed: null})}
                        visible={this.state.outputVisible} closable={false}>
                        <Text>是否导出数据？ID:{this.state.outputSelectedSeed.ID}</Text>
                    </Modal> : null
            }
            {
                this.state.deleteSeedVisible ?
                    <Modal visible={this.state.deleteSeedVisible} closable={false}
                           onOk={() => this._deleteSeed()}
                           onCancel={() => this.setState({deleteSeed: null, deleteSeedVisible: false})}>
                        <Text>是否删除此任务？</Text>
                        <Text>{this.state.deleteSeed.url}</Text>
                    </Modal> : null
            }
            {
                this.state.addSeedVisible ?
                    <Modal visible={this.state.addSeedVisible} closable={false}
                           onOk={() => this._addSeed()}
                           onCancel={() => this.setState({
                               addSeedVisible: false,
                               addSeedName: '', addSeedUrl: '',
                               addSeedParams: '', addSeedFunctionName: ''
                           })}>
                        <Input placeholder={'name'} prefix={<Icon type={'idcard'}/>}
                               onChange={({target}) => this.setState({addSeedName: target.value})}
                               style={{marginBottom: marginBottom}} value={this.state.addSeedName}/>
                        <TextArea placeholder={'url'} style={{marginBottom: marginBottom}}
                                  onChange={({target}) => this.setState({addSeedUrl: target.value})}
                                  value={this.state.addSeedUrl}/>
                        <TextArea placeholder={'params'} style={{marginBottom: marginBottom}}
                                  onChange={({target}) => this.setState({addSeedParams: target.value})}
                                  value={this.state.addSeedParams}/>
                        <Input placeholder={'function_name'} prefix={<Icon type={'code'}/>}
                               onChange={({target}) => this.setState({addSeedFunctionName: target.value})}
                               value={this.state.addSeedFunctionName}
                               style={{marginBottom: marginBottom}}/>
                    </Modal> : null
            }
            {
                this.state.settingsVisible ?
                    <Modal title={'绑定程序'}
                           visible={this.state.settingsVisible} footer={null} width={'90%'} maskClosable={false}
                           onCancel={() => this.setState({settingsVisible: false, selectedSeed: null})}>
                        <Button type={"primary"} style={{marginLeft: 10, marginBottom: 5}}
                                onClick={() => this.getWorkers()}><Icon type={"plus"}/>绑定程序</Button>
                        <Table rowKey={record => record.id}
                               pagination={{
                                   total: this.state.settingCount,
                                   current: this.state.settingCurrent,
                                   pageSize: this.limit,
                                   onChange: (page) => {
                                       this.setState({settingCurrent: page});
                                       this._getSettings(this.state.selectedSeed, (page - 1) * this.limit);
                                   }
                               }}
                               columns={this.settingColumns} dataSource={this.state.settings} footer={null}/>
                        {
                            this.state.bindSeedVisible ?
                                <Modal visible={this.state.bindSeedVisible}
                                       width={1000}
                                       closable={false}
                                       onOk={() => this._bindSeed()}
                                       onCancel={() => this.setState({bindSeedVisible: false})}>
                                    {/*todo: 添加选择功能*/}
                                    <Table rowKey={record => record.id}
                                           columns={this.workerColumns} dataSource={this.state.workers}
                                           pagination={{
                                               total: this.state.workersCount,
                                               current: this.state.workersCurrent,
                                               pageSize: this.limit,
                                               onChange: (page) => {
                                                   this.setState({workersCurrent: page});
                                                   this._getWorkers((page - 1) * this.limit);
                                               }
                                           }}
                                           rowSelection={{
                                               type: 'radio',
                                               onChange: (selectedRowsKey, selectedRows) => {
                                                   this.setState({
                                                       selectedWorker: selectedRows[0],
                                                   });
                                               },
                                           }}/>
                                </Modal> : null
                        }
                    </Modal> : null
            }
            <Text type={"warning"}>需运行对应 任务 的 程序 才可使用</Text>
        </>
    }
}